<?php

namespace App\Console\Commands;

use App\Models\CurveOrderRecord;
use App\Models\Order;
use Carbon\Carbon;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Redis;

class InsertCurveOrder extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'curve_order:insert';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '插入曲线订单';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return int
     */
    public function handle()
    {
        $time = Carbon::now();
        $redis = Redis::connection();
        $last_hour = Carbon::now()->subHour();
        //取上个小时的到达率数据
        $daoda = \App\Models\FlowChannelStat::query()->where([
            'date' =>$last_hour->toDateString(),
            'hour' => $last_hour->hour
        ])->selectRaw('sum(read_num_incr)/sum(pv) as daoda_rate')
            ->first()->daoda_rate;

        //取当前进行中的曲线订单
        Order::query()->where([
            'state' => Order::ORDER_STATE_ON,
            'type' => Order::ORDER_TYPE_CURVE
        ])->get()->each(function ($curve_order) use ($time, $redis, $daoda) {
            //计算当前时间段当前应该期望阅读数
            $expect_read_num = $curve_order->curveOrderRecord()->where('expect_time', '<', $time->addMinutes(5)->format('Y-m-d H:i:00'))
                ->sum('expect_read_num');

            //计算当前订单所需阅读增量
            $expect_read_incr = $expect_read_num - $curve_order->current_read_mnum;

            if ($expect_read_incr > 0) {
                $redis->hset('curve_order_' . $curve_order->id, 'url', $curve_order->url);
                $redis->hset('curve_order_' . $curve_order->id, 'order_id', $curve_order->id);
                $redis->hset('curve_order_' . $curve_order->id, 'expect_read_num', intval($expect_read_incr / $daoda));
                $redis->zadd('curve_order_list', $redis->zcard('curve_order_list'),'curve_order_' . $curve_order->id);
            }
        });
    }
}
